using System.Collections.Generic;
using UnityEngine;

namespace VoxelEngine.TerrainGenerator
{
	public class TreeProp : VoxelProp
	{
		private static List<float> distanceDistribution = new List<float>
		{
			0.468f,
			0.383f,
			0.292f,
			0.197f,
			0.099f
		};

		public override void TryAdd(int wx, int wy, int wz)
		{
			if (Random.Range(0, 30) == 1)
			{
				_position.Add(new Vector3Int(wx, wy, wz));
			}
		}

		public override void Draw(World word)
		{
			foreach (Vector3Int item in _position)
			{
				int num = Random.Range(8, 12);
				int num2 = num - 1;
				for (int i = 1; i < num; i++)
				{
					word[item.x, item.y + i, item.z].Type = BlockType.Wood;
				}
				BlockType foliageFromFoliageDistribution = GetFoliageFromFoliageDistribution();
				TryCreatingFoliage(word, item.x, item.y + num2, item.z, foliageFromFoliageDistribution);
				word.RefreshChunkMesh(word[item.x, item.y + 1, item.z], null);
			}
		}

		private void TryCreatingFoliage(World world, int wx, int wy, int wz, BlockType foliageType)
		{
			for (int i = -2; i < 3; i++)
			{
				for (int j = -2; j < 3; j++)
				{
					for (int k = -2; k < 3; k++)
					{
						if (Mathf.Abs(i) < 2 && Mathf.Abs(j) < 2 && Mathf.Abs(k) < 2)
						{
							TrySetFoliage(world, wx + i, wy + j, wz + k, foliageType);
							continue;
						}
						int num = Mathf.Abs(i) + Mathf.Abs(j) + Mathf.Abs(k);
						if (Random.Range(0f, 1f) < distanceDistribution[num - 2])
						{
							TrySetFoliage(world, wx + i, wy + j, wz + k, foliageType);
						}
					}
				}
			}
			if (world[wx, wy, wz].Type == BlockType.Air)
			{
				world[wx, wy, wz].Type = foliageType;
			}
		}

		private void TrySetFoliage(World world, int wx, int wy, int wz, BlockType foliageType)
		{
			if (world[wx, wy, wz].Type == BlockType.Air || world[wx, wy, wz].Type == BlockType.Height)
			{
				world[wx, wy, wz].Type = foliageType;
			}
		}

		private BlockType GetFoliageFromFoliageDistribution()
		{
			float num = Random.Range(0f, 1f);
			if (num < 0.95f)
			{
				return BlockType.Foliage;
			}
			if (num < 0.98f)
			{
				return BlockType.BlueFoliage;
			}
			if (num < 0.99f)
			{
				return BlockType.RedFoliage;
			}
			return BlockType.LightGreenFoliage;
		}
	}
}
